import { Controller, Get, Post, Query, UploadedFile, UploadedFiles } from "@nestjs/common";
import { ApiBearerAuth, ApiBody, ApiConsumes, ApiOperation, ApiQuery, ApiResponse, ApiTags } from "@nestjs/swagger";
import { FileService } from "./file.service";
import { upload, fileMimetypeFilter, uploads } from "./config/upload.config";
import { CreateFileDto, CreateFilesDto } from "./dto/create-file.dto";
import type { Express } from "express";

@Controller("file")
@ApiTags("文件相关")
export class FileController {
  constructor(private readonly fileService: FileService) {}

  // * 单文件上传
  @Post("upload")
  @ApiOperation({ summary: "单文件上传", description: "单文件上传,限制个数：1,大小：10M" })
  @ApiResponse({ status: 200, description: "fileInfo" })
  @ApiBody({ type: CreateFileDto })
  @ApiConsumes("multipart/form-data")
  @ApiBearerAuth()
  @upload("file", {
    // limits: 对文件大小,文件名大小等限制
    limits: { fileSize: Math.pow(1024, 2) * 10 }, // 10MB 默认1MB
    // fileFilter() 对文件类型验证的函数
    fileFilter: fileMimetypeFilter(["image", "video", "document"]),
  })
  uploadFile(@UploadedFile() file: Express.Multer.File) {
    return this.fileService.uploadFile(file);
  }

  // * 多文件上传
  @Post("uploads")
  @ApiOperation({ summary: "多文件上传", description: "多文件上传,限制个数：5,大小：10M" })
  @ApiResponse({ status: 200, description: "filesInfo" })
  @ApiBody({ type: CreateFilesDto })
  @ApiConsumes("multipart/form-data")
  @ApiBearerAuth()
  @uploads("files", 5, {
    // limits: 对文件大小,文件名大小等限制
    limits: { fileSize: Math.pow(1024, 2) * 10 }, // 10MB 默认1MB
    // fileFilter() 对文件类型验证的函数
    fileFilter: fileMimetypeFilter(["image", "video", "document"]),
  })
  uploadFiles(@UploadedFiles() files: Array<Express.Multer.File>) {
    return this.fileService.uploadFiles(files);
  }

  // * 大文件上传
  @Post("big/upload")
  @ApiOperation({ summary: "大文件上传", description: "大文件上传,大小：6GB (swagger 无法切片)" })
  @ApiResponse({ status: 200, description: "success" })
  @ApiBody({ type: CreateFileDto })
  @ApiConsumes("multipart/form-data")
  @ApiBearerAuth()
  @upload("chunks", {
    // limits: 对文件大小,文件名大小等限制
    limits: { fileSize: Math.pow(1024, 2) * 1024 * 6 }, // 6GB 默认1MB
    // fileFilter() 对文件类型验证的函数
    fileFilter: fileMimetypeFilter(["stream"]),
  })
  uploadBigFiles(@UploadedFile() file: Express.Multer.File) {
    return this.fileService.uploadBigFile(file);
  }

  // * 合并大文件
  @Get("merge")
  @ApiQuery({ name: "文件hash" })
  @ApiOperation({ summary: "合并大文件", description: "调用大文件上传接口完成后需要合并大文件" })
  @ApiResponse({ status: 200, description: "success" })
  @ApiBearerAuth()
  async mergeFile(@Query("hash") hash: string) {
    return await this.fileService.mergeFile(hash);
  }
}
